package com.mediacloud.app.newsmodule.fragment


import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.os.Bundle
import android.text.InputFilter
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.mediacloud.app.assembly.views.TimeLineRelativeLayout
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.ServiceNavigationBtn
import com.mediacloud.app.model.eventbus.event.LoginEvent
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.ServiceCategoryAdapter
import com.mediacloud.app.newsmodule.adaptor.ServiceNavigationListAdapter
import com.mediacloud.app.newsmodule.fragment.baoliao.TransUtils
import com.mediacloud.app.newsmodule.fragment.baoliao.api.MemberApi
import com.mediacloud.app.newsmodule.model.ServiceCategoryListMode
import com.mediacloud.app.newsmodule.model.ServiceManagerListMode
import com.mediacloud.app.newsmodule.utils.ToastUtil
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.controller.SignInController
import com.mediacloud.app.user.interfaces.ILoginStateRefreshResult
import com.mediacloud.app.user.model.UserInfo
import com.mediacloud.app.user.utils.RxUtils
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.utils.DeviceUtils
import com.zimeiti.utils.ActUtil
import kotlinx.android.synthetic.main.fragment_service_navigation.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.util.regex.Pattern


/**
 * 强军号服务导航
 */
class ServiceNavigationFragment : HqyNavFragment(), ToolBarActionF5OrTop,
    OnRefreshLoadMoreListener {


    var name: String = ""
    var category: Int = 0
    var authorType: String = ""
    var catalogID: String? = null
    var deviceId: String? = null
    var deviceName: String? = null
    var loginAddress: String? = ""

    protected var catalogItem: CatalogItem? = null
    val serviceNavigationListAdapter1: ServiceNavigationListAdapter by lazy {
        ServiceNavigationListAdapter(R.layout.adapter_service_navigation_layout)
    }
    val serviceNavigationListAdapter2: ServiceNavigationListAdapter by lazy {
        ServiceNavigationListAdapter(R.layout.adapter_service_navigation_layout)
    }
    val serviceCategoryAdapter: ServiceCategoryAdapter by lazy {
        ServiceCategoryAdapter(R.layout.adapter_service_category_item)
    }
    val imm: InputMethodManager by lazy {
        requireContext().getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
    }
    val signInController = SignInController()

    override fun getLayoutResID(): Int {
        return R.layout.fragment_service_navigation
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (!EventBus.getDefault().isRegistered(context)) {
            EventBus.getDefault().register(this)
        }
        navPaddingTopMatch()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments!!.getString("id")
            catalogItem = saveInstanceArguments!!.getParcelable("catalog")
        }
        recyclerView.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        serviceNavigationListAdapter1.bindToRecyclerView(recyclerView)
        serviceNavigationListAdapter1.searchFlag = true

        resultsRecycler.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        serviceNavigationListAdapter2.bindToRecyclerView(resultsRecycler)
        serviceNavigationListAdapter2.searchFlag = false

        hotSearchRecycler.layoutManager =
            GridLayoutManager(context, 3)
        serviceCategoryAdapter.bindToRecyclerView(hotSearchRecycler)

        serviceCategoryAdapter.setOnItemChildClickListener { adapter, view, position ->
            val dataBean = adapter.data[position] as ServiceCategoryListMode.DataBean
            name = ""
            category = dataBean.id
            serviceCategoryAdapter.currPosition = position
            serviceCategoryAdapter.notifyDataSetChanged()
        }
        getListData(true)
    }

    override fun initView() {
        deviceId = DeviceUtils.getUuid(context, false)
        deviceName = DeviceUtils.getBuildBrandModel()
        if (AppFactoryGlobalConfig.location != null) {
            loginAddress = AppFactoryGlobalConfig.location.city
        }
        loadingView = findViewById(R.id.mLoadingView)
        initStateView()
        retryTips?.setOnClickListener {
            // if (currentState != TYPE_LOADING) {
            showStateView(TYPE_LOADING, false)
            onRefresh(smartRefreshLayout)
            // }
        }
        smartRefreshLayout.setEnableLoadMore(false)
        bottomView.setOnClickListener {
            closeView()
        }
        cancel.setOnClickListener {
            closeView()
        }
        ll_nav_type.setOnClickListener {
            if (hotSearchRecycler.isVisible) {
                hotSearchRecycler.visibility = View.GONE
                btn.visibility = View.GONE
                // 顺时针旋转180度
                val objectAnimator =
                    ObjectAnimator.ofFloat(iv_nav_triangle_type, "rotation", 180f, 0f)
                objectAnimator.setDuration(300).start()
            } else {
                hotSearchRecycler.visibility = View.VISIBLE
                btn.visibility = View.VISIBLE
                // 逆时针旋转180度
                val objectAnimator =
                    ObjectAnimator.ofFloat(iv_nav_triangle_type, "rotation", 0f, 180f)
                objectAnimator.setDuration(300).start()
            }
        }
        tv_dialog_nav_reset.setOnClickListener {
            name = ""
            category = 0
            serviceCategoryAdapter.currPosition = -1
            serviceCategoryAdapter.notifyDataSetChanged()
            tv_nav_type.setTextColor(ContextCompat.getColor(requireContext(), R.color._222))
            iv_nav_triangle_type.setImageResource(R.drawable.icon_triangle_down)
        }
        tv_dialog_nav_yes.setOnClickListener {
            if (category == 0) {
                ToastUtil.show(context, "请选择分类")
                return@setOnClickListener
            }
            searchText.setText("")
            if (hotSearchRecycler.isVisible) {
                hotSearchRecycler.visibility = View.GONE
                btn.visibility = View.GONE
                // 顺时针旋转180度
                val objectAnimator =
                    ObjectAnimator.ofFloat(iv_nav_triangle_type, "rotation", 180f, 0f)
                objectAnimator.setDuration(300).start()
            }
            if (!TextUtils.isEmpty(name) || category != 0) {
                tv_nav_type.setTextColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.cctv7_red
                    )
                )
                iv_nav_triangle_type.setImageResource(R.drawable.icon_triangle_down_red)
            } else {
                tv_nav_type.setTextColor(ContextCompat.getColor(requireContext(), R.color._222))
                iv_nav_triangle_type.setImageResource(R.drawable.icon_triangle_down)
            }

            getListData(false)
        }

        setEditTextInhibitInputSpeChat(searchText)
        searchText.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->

            val b =
                actionId == EditorInfo.IME_ACTION_SEARCH || event != null && event.keyCode == KeyEvent.KEYCODE_ENTER
            if (b) {
                if (searchText != null) {
                    if (TextUtils.isEmpty(searchText.text.toString())) {
                        ToastUtil.show(context, "请输入关键字")
                        return@OnEditorActionListener false
                    }
                    if (!TextUtils.isEmpty(searchText.text.toString())) {
                        name = searchText.text.toString()
                        category = 0
                        serviceCategoryAdapter.currPosition = -1
                        serviceCategoryAdapter.notifyDataSetChanged()
                        hotSearchRecycler.visibility = View.GONE
                        btn.visibility = View.GONE
                        tv_nav_type.setTextColor(
                            ContextCompat.getColor(
                                requireContext(),
                                R.color._222
                            )
                        )
                        iv_nav_triangle_type.setImageResource(R.drawable.icon_triangle_down)
                        getListData(false)
                        return@OnEditorActionListener true
                    }

                }
            }
            false
        })
        showStateView(TYPE_LOADING, false)
        smartRefreshLayout.setOnRefreshLoadMoreListener(this)


    }

    private fun getListData(flag: Boolean) {
        if (UserInfo.isLogin(activity)) {
            val userInfo = UserInfo.getUserInfo(activity)
            if (userInfo.spider_user_type != null && userInfo.spider_user_type == "1") {
                authorType = ""
                //普通用户
                getData(flag)
            } else {
                //融媒号
                getAuthorTypeId()
            }
        } else {
            authorType = ""
            getData(flag)
        }
    }

    private fun closeView() {
        name = ""
        category = 0
        serviceCategoryAdapter.currPosition = -1
        serviceCategoryAdapter.notifyDataSetChanged()
        searchText.setText("")
        tv_nav_type.setTextColor(ContextCompat.getColor(requireContext(), R.color._222))
        iv_nav_triangle_type.setImageResource(R.drawable.icon_triangle_down)
        if (searchView.isVisible) {
            searchView.visibility = View.GONE
        }
        if (resultsRecycler.isVisible) {
            resultsRecycler.visibility = View.GONE
        }
        if (hotSearchRecycler.isVisible) {
            hotSearchRecycler.visibility = View.GONE
        }
        if (btn.isVisible) {
            btn.visibility = View.GONE
        }

        imm.hideSoftInputFromWindow(searchText?.windowToken, 0)
    }

    @SuppressLint("CheckResult")
    private fun getData(flag: Boolean) {

        val map: MutableMap<String, Any> = HashMap()
        if (!TextUtils.isEmpty(name)) {
            map["name"] = name
        }
        if (!TextUtils.isEmpty(authorType)) {
            map["authorType"] = authorType
        }
        if (category != 0) {
            map["category"] = category
        }
        MemberApi.getMemberApi()
            .getServiceManageList(map)
            .compose(
                TransUtils.fastJSonTransform(
                    ServiceManagerListMode::class.java
                )
            )
            .compose(RxUtils.schedulersTransformer())
            .subscribe(
                {
                    smartRefreshLayout.finishRefresh()
                    closeStateView()
                    Log.w("APPTAG", "$it")
                    if (flag) {
                        serviceNavigationListAdapter1.setNewData(it.data)
                    } else {
                        imm.hideSoftInputFromWindow(searchText?.windowToken, 0)
                        resultsRecycler.visibility = View.VISIBLE
                        serviceNavigationListAdapter2.setNewData(it.data)
                    }
                },
                {
                    smartRefreshLayout.finishRefresh()
                    Log.w("APPTAG", "$it")
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                }
            )

    }

    @SuppressLint("CheckResult")
    private fun getCategory() {

        MemberApi.getMemberApi()
            .serviceCategoryList
            .compose(
                TransUtils.fastJSonTransform(
                    ServiceCategoryListMode::class.java
                )
            )
            .compose(RxUtils.schedulersTransformer())
            .subscribe(
                {
                    closeStateView()
                    Log.w("APPTAG", "$it")
                    serviceCategoryAdapter.setNewData(it.data)
                    if (it.data.size == 0) {
                        showStateView(TYPE_NO_CONTENT, false)
                    }
                },
                {
                    Log.w("APPTAG", "$it")
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                }
            )

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun loginState(loginEvent: LoginEvent?) {
        getListData(true)
    }

    fun getAuthorTypeId() {
        val userInfo = UserInfo.getUserInfo(requireContext())
        if (userInfo != null) {
            signInController.autoSaveUserInfo = true
            signInController.refreshLoginInfo(
                userInfo.token,
                userInfo.userid,
                userInfo.platform,
                true, deviceId, deviceName, loginAddress,
                object : ILoginStateRefreshResult<UserInfo> {
                    override fun userExpired(p0: String?) {

                    }

                    override fun loginStateRefreshSuccess(p0: UserInfo?) {
                        p0?.let {
                            val jsonObject = JSONObject(p0.originData)
                            authorType = jsonObject.optString("authorTypeId")
                        }
                        getData(true)
                    }

                    override fun loginStateRefreshFailed(p0: String?) {

                    }

                }
            )
        }
    }


    fun refresh(list: List<ServiceManagerListMode.DataBean>) {
        serviceNavigationListAdapter1.setNewData(list)
    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        TimeLineRelativeLayout.headList.clear()
        getListData(true)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun negationDelete(data: ServiceNavigationBtn) {
        if (!searchView.isVisible) {
            searchView.visibility = View.VISIBLE
            searchText.isFocusable = true
            searchText.isFocusableInTouchMode = true
            searchText.requestFocus()
            imm.showSoftInput(searchText, 0)
        }
        getCategory()
    }

    override fun f5() {
        recyclerView.scrollToPosition(0)
        smartRefreshLayout.setEnableRefresh(true)
        smartRefreshLayout.autoRefresh(200)
    }

    override fun gun() {
    }

    /**
     * 禁止EditText输入特殊字符
     *
     * @param editText
     */
    fun setEditTextInhibitInputSpeChat(editText: EditText) {
        val filter =
            InputFilter { source, start, end, dest, dstart, dend -> //                String speChat = "[`~!@#$%^&*()+=|{}\\[\\]<>/~！@#￥%&*|{}【】]";
                val speChat = "[`~!@#$%^&*()|{}\\[\\]<>/~#%&*|{}【】]"
                val pattern = Pattern.compile(speChat)
                val matcher = pattern.matcher(source.toString())
                if (matcher.find()) "" else null
            }
        editText.filters = arrayOf(filter)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (EventBus.getDefault().isRegistered(context)) {
            EventBus.getDefault().unregister(this)
        }
    }
}